var express = require("express");
var Category = require("../models/category");
var router = express.Router();

var db = require("../libs/index.js");
var Mqtt = require("../models/mqtt.model")(db.sequelize, db.Sequelize);
function isString(obj){ //判断对象是否是字符串
  return Object.prototype.toString.call(obj) === "[object String]";
}

// 添加传感器历史数据
router.post("/", async function (req, res) {
  // console.log('req.body',req.body)
  // 接受从mqtx的webhook传过来的数据,可能是字符串，需要转json格式
  const payload = isString(req.body.payload)?JSON.parse(req.body.payload):req.body.payload ;
  // console.log("payload", payload);
  if (!payload) return;
  const data = payload;
  // console.log(payload, data);
  // const data = {name: req.body.name,device_id:req.body.device_id}
  var category = new Category(data);
  await category.save(function (err) {
    if (err) {
      res.status(500).json({
        success: false,
        message: "添加传感器失败！",
      });
    }
  });
  var condition = data.device_id
    ? { device_id:data.device_id }
    : null;
  const sqlmodel = await Mqtt.update(data, { where: condition });
  console.log(sqlmodel);
  if (sqlmodel[0] === 1) {
    console.log("更新到mysql成功");
  } else {
    console.log("更新到mysql失败");
  }
});

// 查看所有传感器
router.get("/", async function (req, res) {
  let skip = 0,
    limit = 100;
  if (req.query && req.query.skip && req.query.limit) {
    skip = req.query.skip;
    limit = req.query.limit;
  }

  const data = await Category.find()
    .skip(skip)
    .limit(limit)
    .sort({ createdAt: "desc" });
  res.json({
    success: true,
    data: data,
  });
});

// 根据id查询
router.get("/:id", async (req, res) => {
  // console.log(req.query)
  const limit = +req.query.limit || 100;
  const model = await Category.findById(req.params.id).limit(limit);
  res.json(model);
});
// 根据id修改资源
router.put("/:id", async (req, res) => {
  // console.log(req.query)
  const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
  res.json(model);
});
// 根据id删除
router.delete("/:id", async (req, res) => {
  // console.log(req.query)
  const model = await req.Model.findByIdAndDelete(req.params.id, req.body);
  res.send({
    model,
    success: true,
  });
});

module.exports = router;
